package com.macrog.rabbitmq.work;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * Created by Administrator on 2018/9/1.
 */
public class Recv1 {

    private static final String QUEUE_NAME = "work";

    public static void main(String[] args) throws IOException, TimeoutException {
        //1、创建连接工厂
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("192.168.31.227");
        factory.setVirtualHost("/macrog");
        factory.setUsername("macrog");
        factory.setPassword("macrog");

        //2、创建连接
        Connection connection = factory.newConnection();

        //3、创建channel
        final Channel channel = connection.createChannel();

        //4、申明队列
        channel.queueDeclare(QUEUE_NAME,false,false,false,null);

        //5、创建消费者监听
        Consumer consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                String message = new String(body, "UTF-8");
                System.out.println("消费者1收到消息："+message+",开始进入工作");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                //参数2false为确认收到消息
                channel.basicAck(envelope.getDeliveryTag(), false);
            }
        };

        //6、注册消费者，参数2flase为手动应答，收到消息后需要告诉生产者
        channel.basicConsume(QUEUE_NAME,false, consumer);
    }
}
